<?php

/**
 * {0}
 *
 * @author longpt
 * @version
 */

require_once "BaseModel.php";
require_once "IUser.php";
require_once 'DBUtils.php';

class RecoverToken extends BaseModel
{
	/**
	 * The default table name
	 */
	protected $_name = 'passRecoverToken';
	protected $_primary = 'token';

	public function insertToken($userID)	{
		$token = Utils::createPasswordRecoverToken($userID);
		$data = array('userID'=>$userID, 'token'=>$token);
		$rs = $this->insertRowWithData($data);
		if ($rs == false)
			return false;
		return $token;
	}
	
	public function isTokenValid($token)	{
		$stmt = $this->select()->where('token = :_token')->bind(array(':_token'=>$token));
		$rs = $this->fetchRow($stmt);
		if ($rs == null)	{
			return false;
		}
		$current_date = time();
		$date = $rs->created_date;
		list($d,$t) = explode(' ',$date);
		$dateArr  = explode("-",$d);
		$timeArr = explode(":",$t);
		$date1Int = mktime($timeArr[0],$timeArr[1],$timeArr[2],$dateArr[1],$dateArr[2],$dateArr[0]) ;
		$date_diff = $current_date - $date1Int;
		if ($date_diff > 24*3600)	{
			return false;
		}
		return $rs->userID;
	}
	
	public function deleteToken($token)	{
		$token = $this->clean($token);
		$this->delete(array('token = "'.$token.'"'));
	}
}